﻿using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using Neo4JConnector.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Neo4JConnector
{
    [Icon("pack://application:,,,/Neo4JConnector;component/Resources/Icon.png")]
    [Category("neo4j图数据库")]
    [OrderWeight(999)]
    public class ExecCypher : BaseNeo4JOp, IServerCommandParamGenerator
    {

        [FormulaProperty]
        [DisplayName("Cypher语句")]
        [OrderWeight(100)]
        [SearchableProperty]
        public object CypherExpr { get; set; }

      
        [DisplayName("将执行结果保存到变量")]
        [OrderWeight(999)]
        [ResultToProperty]
        public string ResultInParamater { get; set; } = "Results";

        public override async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var cypher = (await dataContext.EvaluateFormulaAsync(CypherExpr))?.ToString() ?? "";

            if (string.IsNullOrEmpty(cypher))
            {
                throw new Exception("Cypher语句不能为空。");
            }

            var client = await getClient(dataContext);
            var data = await client.ExecuteCypherAsync(cypher);

            if (!string.IsNullOrEmpty(ResultInParamater))
            {
                dataContext.Parameters[ResultInParamater] = data;
            }

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "neo4j：执行Cypher语句";
        }

        public IEnumerable<GenerateParam> GetGenerateParams()
        {
            yield return new GenerateObjectParam()
            {
                ParamName = this.ResultInParamater,
                Description = "Cypher语句的执行结果",
                ParamScope = CommandScope.All,
                SubPropertiesDescription = new Dictionary<string, string>() {
                    { "Records","查询结果"},
                    { "Summary","执行过程的概况"},
                    { "NodesCreated","创建的节点数"},
                    { "NodesDeleted","删除的节点数"},
                    { "RelationshipsCreated","创建的关系数"},
                    { "RelationshipsDeleted","删除的关系数"}
                }
            };
        }
    }
}
